require 'RMagick'

class Store < ActiveRecord::Base
	belongs_to :merchant
	has_many :props, :class_name => 'StoreExt', :foreign_key => 'store_ext_id'
  
	validates_presence_of :name, :message => "必须填写快印店名称"
	validates_presence_of :address, :message => "必须填写快印店地址"
	validates_presence_of :province, :message => "必须填写快印店所在省"
	validates_presence_of :city, :message => "必须填写快印店所在市"
	validates_presence_of :area, :message => "必须填写快印店所在区"
	validates_presence_of :phone, :message => "必须填写快印店联系电话"
	validates_presence_of :work_time, :message => "必须填写快印店营业时间"
  
  @@image_store_path = "#{RAILS_ROOT}/public"
  
	def upload_logo=(file)
		# 96x96>表示如果图片比这个尺寸小就不缩放
		file_path, file_app_path, file_name = upload_image('logo', file)
    resize(file_path, '96x96>')
    resize(file_path, '48x48>', file_app_path + "small_" +file_name)
		self.logo = file_path unless file_path.nil?
	end

	def upload_logo
		self.logo
	end

	def upload_store_image=(file)
		file_path, file_app_path, file_name = upload_image('store_image', file)
    resize(file_path, '300x300>')
		self.store_image = file_path unless file_path.nil?
	end

	def upload_store_image
		self.store_image
	end

	def upload_license=(file)
		file_path, file_app_path, file_name = upload_image('license', file)
    resize(file_path, '800x800>')
		self.license = file_path unless file_path.nil?
	end

	def upload_license
		self.license
	end

	# 列出最新加入的商店
	def Store.list_recently_join(size = 5)
		Store.find(:all, :conditions => 'disabled = false AND passed = true', :limit => size, :order => "created_at DESC")
	end
  
	private
	def upload_image(image_type, file)
		if file != nil && file != ""
      # 用时间戳生成文件名
			file_name = (Time.now.to_i + rand(1000)).to_s + File.extname(file.original_filename)
			# 网页上显示时用此地址
			file_app_path = "/images/store/#{image_type}/"
			file_path = file_app_path + file_name
			# 用绝对地址写入文件
      File.open(@@image_store_path + file_path, 'wb') do |f|
				f.write(file.read)
			end
			return file_path, file_app_path, file_name
		end
	end
  
  def resize(file_path, size, new_file_path = nil)
    unless size.nil?
				#对图片进行缩放处理
				img_orig = Magick::Image.read(@@image_store_path + file_path).first
				new_img = img_orig.change_geometry!(size) { |cols, rows, img|
					img.resize!(cols, rows)
				}
        # 如果没有指名新的文件名，那么将覆盖老的文件
				new_img.write(@@image_store_path + (new_file_path == nil ? file_path : new_file_path))
			end
  end
end
